from data_provider.data_factory import data_provider
from exp.exp_basic import Exp_Basic
from utils.tools import EarlyStopping, adjust_learning_rate, visual
from utils.metrics import metric
import torch
import torch.nn as nn
from torch import optim
import os
import time
import warnings
import numpy as np
from utils.dtw_metric import dtw, accelerated_dtw
from utils.augmentation import run_augmentation, run_augmentation_single
import pandas as pd
import pandas as pd  # 确保没有拼写错误（如 `import pands as pd`）
warnings.filterwarnings('ignore')


class Exp_Long_Term_Forecast(Exp_Basic):
    def __init__(self, args):
        super(Exp_Long_Term_Forecast, self).__init__(args)

    def _build_model(self):
        model = self.model_dict[self.args.model].Model(self.args).float()

        if self.args.use_multi_gpu and self.args.use_gpu:
            model = nn.DataParallel(model, device_ids=self.args.device_ids)
        return model

    def _get_data(self, flag):
        data_set, data_loader = data_provider(self.args, flag)
        return data_set, data_loader

    def _select_optimizer(self):
        model_optim = optim.Adam(self.model.parameters(), lr=self.args.learning_rate)
        return model_optim

    def _select_criterion(self):
        criterion = nn.MSELoss()
        return criterion

    def vali(self, vali_data, vali_loader, criterion):
        total_loss = []
        self.model.eval()
        with torch.no_grad():
            for i, (batch_x, batch_y, batch_x_mark, batch_y_mark) in enumerate(vali_loader):
                batch_x = batch_x.float().to(self.device)
                batch_y = batch_y.float()

                batch_x_mark = batch_x_mark.float().to(self.device)
                batch_y_mark = batch_y_mark.float().to(self.device)

                # decoder input
                dec_inp = torch.zeros_like(batch_y[:, -self.args.pred_len:, :]).float()
                dec_inp = torch.cat([batch_y[:, :self.args.label_len, :], dec_inp], dim=1).float().to(self.device)
                # encoder - decoder
                if self.args.use_amp:
                    with torch.cuda.amp.autocast():
                        outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
                else:
                    outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
                f_dim = -1 if self.args.features == 'MS' else 0
                outputs = outputs[:, -self.args.pred_len:, f_dim:]
                batch_y = batch_y[:, -self.args.pred_len:, f_dim:].to(self.device)

                pred = outputs.detach().cpu()
                true = batch_y.detach().cpu()

                loss = criterion(pred, true)

                total_loss.append(loss)
        total_loss = np.average(total_loss)
        self.model.train()
        return total_loss

    def train(self, setting):
        train_data, train_loader = self._get_data(flag='train')
        vali_data, vali_loader = self._get_data(flag='val')
        test_data, test_loader = self._get_data(flag='test')

        path = os.path.join(self.args.checkpoints, setting)
        if not os.path.exists(path):
            os.makedirs(path)

        time_now = time.time()

        train_steps = len(train_loader)
        early_stopping = EarlyStopping(patience=self.args.patience, verbose=True)

        model_optim = self._select_optimizer()
        criterion = self._select_criterion()

        if self.args.use_amp:
            scaler = torch.cuda.amp.GradScaler()

        for epoch in range(self.args.train_epochs):
            iter_count = 0
            train_loss = []

            self.model.train()
            epoch_time = time.time()
            for i, (batch_x, batch_y, batch_x_mark, batch_y_mark) in enumerate(train_loader):
                iter_count += 1
                model_optim.zero_grad()
                batch_x = batch_x.float().to(self.device)
                batch_y = batch_y.float().to(self.device)
                batch_x_mark = batch_x_mark.float().to(self.device)
                batch_y_mark = batch_y_mark.float().to(self.device)

                # decoder input
                dec_inp = torch.zeros_like(batch_y[:, -self.args.pred_len:, :]).float()
                dec_inp = torch.cat([batch_y[:, :self.args.label_len, :], dec_inp], dim=1).float().to(self.device)

                # encoder - decoder
                if self.args.use_amp:
                    with torch.cuda.amp.autocast():
                        outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)

                        f_dim = -1 if self.args.features == 'MS' else 0
                        outputs = outputs[:, -self.args.pred_len:, f_dim:]
                        batch_y = batch_y[:, -self.args.pred_len:, f_dim:].to(self.device)
                        loss = criterion(outputs, batch_y)
                        train_loss.append(loss.item())
                else:
                    outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)

                    f_dim = -1 if self.args.features == 'MS' else 0
                    outputs = outputs[:, -self.args.pred_len:, f_dim:]
                    batch_y = batch_y[:, -self.args.pred_len:, f_dim:].to(self.device)
                    loss = criterion(outputs, batch_y)
                    train_loss.append(loss.item())

                if (i + 1) % 100 == 0:
                    print("\titers: {0}, epoch: {1} | loss: {2:.7f}".format(i + 1, epoch + 1, loss.item()))
                    speed = (time.time() - time_now) / iter_count
                    left_time = speed * ((self.args.train_epochs - epoch) * train_steps - i)
                    print('\tspeed: {:.4f}s/iter; left time: {:.4f}s'.format(speed, left_time))
                    iter_count = 0
                    time_now = time.time()

                if self.args.use_amp:
                    scaler.scale(loss).backward()
                    scaler.step(model_optim)
                    scaler.update()
                else:
                    loss.backward()
                    model_optim.step()

            print("Epoch: {} cost time: {}".format(epoch + 1, time.time() - epoch_time))
            train_loss = np.average(train_loss)
            vali_loss = self.vali(vali_data, vali_loader, criterion)
            test_loss = self.vali(test_data, test_loader, criterion)

            print("Epoch: {0}, Steps: {1} | Train Loss: {2:.7f} Vali Loss: {3:.7f} Test Loss: {4:.7f}".format(
                epoch + 1, train_steps, train_loss, vali_loss, test_loss))
            early_stopping(vali_loss, self.model, path)
            if early_stopping.early_stop:
                print("Early stopping")
                break

            adjust_learning_rate(model_optim, epoch + 1, self.args)

        best_model_path = path + '/' + 'checkpoint.pth'
        self.model.load_state_dict(torch.load(best_model_path))

        return self.model

    def test(self, setting, test=0):
        test_data, test_loader = self._get_data(flag='test')
        if test:
            print('loading model')
            self.model.load_state_dict(torch.load(os.path.join('./checkpoints/' + setting, 'checkpoint.pth')))

        preds = []
        trues = []
        inputs = []  # Store input sequences for reference
        sample_indices = []  # Store indices for sample identification

        folder_path = './test_results/' + setting + '/'
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

        self.model.eval()
        with torch.no_grad():
            for i, (batch_x, batch_y, batch_x_mark, batch_y_mark) in enumerate(test_loader):
                batch_x = batch_x.float().to(self.device)
                batch_y = batch_y.float().to(self.device)

                batch_x_mark = batch_x_mark.float().to(self.device)
                batch_y_mark = batch_y_mark.float().to(self.device)

                # decoder input
                dec_inp = torch.zeros_like(batch_y[:, -self.args.pred_len:, :]).float()
                dec_inp = torch.cat([batch_y[:, :self.args.label_len, :], dec_inp], dim=1).float().to(self.device)
                # encoder - decoder
                if self.args.use_amp:
                    with torch.cuda.amp.autocast():
                        outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)
                else:
                    outputs = self.model(batch_x, batch_x_mark, dec_inp, batch_y_mark)

                f_dim = -1 if self.args.features == 'MS' else 0
                outputs = outputs[:, -self.args.pred_len:, :]
                batch_y = batch_y[:, -self.args.pred_len:, :].to(self.device)

                # Save inputs for reference
                input_np = batch_x.detach().cpu().numpy()

                # Convert to numpy
                outputs_np = outputs.detach().cpu().numpy()
                batch_y_np = batch_y.detach().cpu().numpy()

                # Handle inverse transformation if needed
                if test_data.scale and self.args.inverse:
                    shape = batch_y_np.shape
                    if outputs_np.shape[-1] != batch_y_np.shape[-1]:
                        outputs_np = np.tile(outputs_np, [1, 1, int(batch_y_np.shape[-1] / outputs_np.shape[-1])])
                    outputs_np = test_data.inverse_transform(outputs_np.reshape(shape[0] * shape[1], -1)).reshape(shape)
                    batch_y_np = test_data.inverse_transform(batch_y_np.reshape(shape[0] * shape[1], -1)).reshape(shape)
                    input_np = test_data.inverse_transform(
                        input_np.reshape(input_np.shape[0] * input_np.shape[1], -1)).reshape(input_np.shape)

                outputs_np = outputs_np[:, :, f_dim:]
                batch_y_np = batch_y_np[:, :, f_dim:]

                pred = outputs_np
                true = batch_y_np

                # Store batch info with identifiers
                for j in range(pred.shape[0]):
                    sample_indices.append(i * batch_x.shape[0] + j)
                    inputs.append(input_np[j])
                    preds.append(pred[j])
                    trues.append(true[j])

                # Visualize a subset of the results
                # if i % 20 == 0:
                #     if test_data.scale and self.args.inverse:
                #         input_viz = input_np
                #     else:
                #         input_viz = input_np
                #     gt = np.concatenate((input_viz[0, :, -1], true[0, :, -1]), axis=0)
                #     pd = np.concatenate((input_viz[0, :, -1], pred[0, :, -1]), axis=0)
                #     visual(gt, pd, os.path.join(folder_path, str(i) + '.pdf'))

        # Create result directory
        folder_path = './results/' + setting + '/'
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)

        # DTW calculation
        if self.args.use_dtw:
            dtw_list = []
            manhattan_distance = lambda x, y: np.abs(x - y)
            for i in range(len(preds)):
                x = preds[i].reshape(-1, 1)
                y = trues[i].reshape(-1, 1)
                if i % 100 == 0:
                    print("calculating dtw iter:", i)
                d, _, _, _ = accelerated_dtw(x, y, dist=manhattan_distance)
                dtw_list.append(d)
            dtw = np.array(dtw_list).mean()
        else:
            dtw = 'Not calculated'

        # Prepare data for metrics calculation
        preds_array = np.array(preds)
        trues_array = np.array(trues)

        # Calculate metrics
        mae, mse, rmse, mape, mspe = metric(preds_array, trues_array)
        print('mse:{}, mae:{}, dtw:{}'.format(mse, mae, dtw))

        # Save metrics to file
        f = open("result_long_term_forecast.txt", 'a')
        f.write(setting + "  \n")
        f.write('mse:{}, mae:{}, dtw:{}'.format(mse, mae, dtw))
        f.write('\n')
        f.write('\n')
        f.close()

        # Save metrics as numpy arrays
        np.save(folder_path + 'metrics.npy', np.array([mae, mse, rmse, mape, mspe]))

        # Save predictions and ground truth in a well-structured format
        # 1. As numpy arrays for compatibility with existing code
        np.save(folder_path + 'pred.npy', preds_array)
        np.save(folder_path + 'true.npy', trues_array)

        # 2. Save as a paired dataset for easier matching
        paired_data = {
            'sample_idx': sample_indices,
            'pred': preds_array,
            'true': trues_array,
            'input': np.array(inputs)
        }
        np.save(folder_path + 'paired_data.npy', paired_data)

        # 3. Save time series data in CSV format for easy analysis
        # This is particularly useful for specific feature analysis
        if self.args.features == 'MS':
            num_features = preds_array.shape[2]
            for f in range(num_features):
                feature_data = []
                for i in range(len(sample_indices)):
                    for t in range(preds_array.shape[1]):  # For each timestep
                        feature_data.append({
                            'sample_idx': sample_indices[i],
                            'timestep': t,
                            'feature': f,
                            'prediction': preds_array[i, t, f],
                            'ground_truth': trues_array[i, t, f]
                        })
                feature_df = pd.DataFrame(feature_data)
                feature_df.to_csv(f'{folder_path}feature_{f}_results.csv', index=False)
        else:
            # For univariate (S) case
            series_data = []
            print("preds_array type:", type(preds_array))
            print("trues_array type:", type(trues_array))
            print("preds_array shape:", preds_array.shape)
            print("trues_array shape:", trues_array.shape)
            for i in range(len(sample_indices)):
                for t in range(preds_array.shape[1]):  # For each timestep
                    series_data.append({
                        'sample_idx': sample_indices[i],
                        'timestep': t,
                        'prediction': preds_array[i, t, 0],
                        'ground_truth': trues_array[i, t, 0]
                    })
            print("series_data type:", type(series_data))
            print("series_data first element:", series_data[0] if series_data else "Empty")
            series_df = pd.DataFrame(series_data)

            series_df.to_csv(f'{folder_path}series_results.csv', index=False)

        # 4. Save a summary that pairs each sample's prediction metrics
        sample_metrics = []
        for i in range(len(sample_indices)):
            sample_pred = preds_array[i]
            sample_true = trues_array[i]
            sample_mae, sample_mse, sample_rmse, sample_mape, sample_mspe = metric(
                sample_pred.reshape(1, sample_pred.shape[0], sample_pred.shape[1]),
                sample_true.reshape(1, sample_true.shape[0], sample_true.shape[1])
            )
            sample_metrics.append({
                'sample_idx': sample_indices[i],
                'mae': sample_mae,
                'mse': sample_mse,
                'rmse': sample_rmse,
                'mape': sample_mape,
                'mspe': sample_mspe
            })
        metrics_df = pd.DataFrame(sample_metrics)
        metrics_df.to_csv(f'{folder_path}sample_metrics.csv', index=False)

        return